import {Component, OnInit} from '@angular/core';
import {LocalDataSource} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {NbDialogRef, NbDialogService} from '@nebular/theme';
import {AdminService} from "../../AdminService";
import {DocService} from "../../energy/api";
import {BaseRequest} from "../../utils/BaseRequest";
import {map} from "rxjs/operators";
import {ResponseLocationInfo} from "../../energy/api/model/responseLocationInfo";

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './location-document.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
    button {
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .margin {
      margin:10px;
    }
  `],
})
export class LocationDocumentComponent implements OnInit{
  settings = {
    pager: {
      display: true,
      perPage: 20
    },
    hideSubHeader: true,
    actions: {
      columnTitle: '操作',
      add: false,
      position: 'right'
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      locationId: {
        title: 'ID',
        type: 'number',
      },
      locationNo: {
        title: '地址编号',
        type: 'string',
      },
      locationName: {
        title: '地址名称',
        type: 'string',
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
      building: {
        title: '楼栋列表',
        type: 'html',
      }
    },
  };
  source: DataDataSource = new DataDataSource(this.api);
  filterLocationNo:string = '';
  filterLocationName:string = '';
  constructor(private service: SmartTableData
              , private api: DocService
              , private dialogService: NbDialogService
              , private admin:AdminService) {

  }

  filter(){
    this.source.locationName = this.filterLocationName;
    this.source.locationNo = this.filterLocationNo;
    this.source.setPage(1);
    this.source.refresh();
  }

  ngOnInit(): void {
  }

  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECASyncLocationInfo(new BaseRequest(
        [{
          operateType: "2",
          locationId: event.data['locationId'],
        }]
    )).toPromise().then(res => {
        if (res.success) {
          event.confirm.resolve();
        } else {
          event.confirm.reject();
        }
      }).catch(e => {
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  onEditConfirm(event): void {
    this.api.postECASyncLocationInfo(new BaseRequest(
      [{
        operateType: "1",
        locationId: event.data['locationId'],
        locationNo: event.newData['locationNo'],
        locationName: event.newData['locationName'],
        extInfo: event.newData['extInfo'],
      }]
  )).toPromise().then(response => {
      console.log(response);
      event.confirm.resolve();
    }).catch(e => {
      console.log(e);
      event.confirm.reject();
    })
  }

  openAddPrompt() {
    this.dialogService.open(LocationAddPrompt)
      .onClose.subscribe(v => {
      if (v == null) return;
      this.api.postECASyncLocationInfo(new BaseRequest(
        [
          {
            operateType: "0",
            locationNo: v['locationNo'],
            locationName: v['locationName'],
            extInfo: v['extInfo'],
          }
        ]
    )).toPromise().then(response => {
        console.log(response);
        this.source.refresh();
      })
    });
  }

}

export class DataDataSource extends LocalDataSource {
  locationNo:string = '';
  locationName:string = '';
  all: number = -1;
  constructor(private api: DocService) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
    };
    if(this.locationNo!='') query['locationNo'] = this.locationNo;
    if(this.locationName!='') query['locationName'] = this.locationName;
    return this.api.requestECALocationInfo(new BaseRequest(query)).pipe(map((res:ResponseLocationInfo)=>{
      this.all = res.dataCount;
      return res.data.map(value=>{
        value['building'] = `<a href="/#/pages/doc/bd/${value.locationId}">查看楼栋</a>`;
        return value;
      });
    })).toPromise();
  }
}


@Component({
  selector: 'location-add-prompt',
  template: `
    <nb-card style="min-width:800px">
      <nb-card-header>新建地址</nb-card-header>
      <nb-card-body>
        <form class="form-group">
          <label>地址编号</label>
          <input #locationNo nbInput fullWidth>
          <label>地址名称</label>
          <input #locationName nbInput fullWidth>
          <label>额外信息</label>
          <input #extInfo nbInput fullWidth>
        </form>
      </nb-card-body>
      <nb-card-footer>
        <button nbButton status="danger" (click)="cancel()">取消</button>
        <button nbButton status="success"
                (click)="submit({'locationNo':locationNo.value,'locationName':locationName.value,'extInfo':extInfo.value})">
          确定
        </button>
      </nb-card-footer>
    </nb-card>
  `,
  styles:[
    `
    button {
      margin:5px;
    }
    `
  ]
})
export class LocationAddPrompt {
  constructor(protected ref: NbDialogRef<LocationAddPrompt>) {
  }

  cancel() {
    this.ref.close();
  }

  submit(result) {
    this.ref.close(result);
  }
}
